import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as CheckManagementService from '../../../axios/CheckManagement'
import * as APIServiceYQ from '../../../axios/api_yq'
import * as APIService from '../../../axios/api'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'

import { statusList } from '../../../utils/global';

import SearchForm from './SearchForm';
import ChooseBill from './ChooseBill';
import { withRouter } from 'react-router';
import { withPermission } from '../../../components/withpermission'
import AddForm from './AddForm';
const ZPButton = withPermission(Button, 'arrow-right')
const CreateButton = withPermission(Button, 'plus')
const PrintButton = withPermission(Button, 'printer')
const DownLoadButton = withPermission(Button, 'download')

class CheckManagement extends Component {
  state = {
    dataSource: [],
    advanced: false,
    userId: localStorage.getItem('userId'),
    searchItem: {},
    pageSize: 10,
    pageNum: 1,
    total: 0,
    statusList: [],
    selectList1: [
      { key: 0, label: '试机' },
      { key: 1, label: '自检' },
      { key: 2, label: '质检' },
    ],  // 表单类型
    selectList2: [
      { key: 0, label: '未开始' },
      { key: 1, label: '进行中' },
      { key: 2, label: '已完成' },
    ],  // 状态
    selectList3: [
      { key: 0, label: '不合格' },
      { key: 1, label: '合格' },
    ],  // 结果
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        width: 50,
        align: 'center',
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '批号',
        dataIndex: 'batchNo',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo)
      },

      {
        title: '装配班组',
        width: 100,
        dataIndex: 'assemblyDept',
        sorter: (a, b) => compareString(a.assemblyDept, b.assemblyDept),
      },
      {
        title: '检验单号',
        width: 180,
        dataIndex: 'checkCode',
        sorter: (a, b) => compareString(a.checkCode, b.checkCode)
      },
      {
        title: '检验表单编码',
        width: 130,
        dataIndex: 'fromCode',
        sorter: (a, b) => compareString(a.fromCode, b.fromCode)
      },
      {
        title: '检验表单名称',
        width: 130,
        dataIndex: 'fromName',
        sorter: (a, b) => compareString(a.fromName, b.fromName)
      },
      {
        title: '检验表单类型',
        width: 130,
        dataIndex: 'fromType',
        sorter: (a, b) => compareString(a.fromType, b.fromType),
        render: (text) => {
          let obj = this.state.selectList1.find(item => item.key == text)
          return obj?.label
        }
      },
      {
        title: '状态',
        width: 100,
        dataIndex: 'state',
        sorter: (a, b) => compareString(a.state, b.state),
        render: (text, record, index) => {
          let a = this.state.selectList2.find(item => item.key == text)
          // return <a style={{ color: text == 0 ? '#BFBFBF' : text == 1 ? '#0E77D1' : text == 2 ? '#00A854' : '#fff' }}>{a?.label}</a>
          return <div style={{ display: 'flex', alignItems: 'center' }}><div style={{ backgroundColor: text == 0 ? '#BFBFBF' : text == 1 ? '#0E77D1' : text == 2 ? '#00A854' : '#fff', width: 5, height: 5, borderRadius: 5 }}></div>&nbsp;{a?.label}</div>
        }
      },
      {
        title: '检验完成时间',
        width: 150,
        dataIndex: 'inspectionCompletionTime',
        ellipsis: true,
        sorter: (a, b) => compareDate(a.inspectionCompletionTime, b.inspectionCompletionTime)
      },
      {
        title: '质检人员',
        width: 100,
        dataIndex: 'assignName',
        ellipsis: true,
        sorter: (a, b) => compareString(a.assignName, b.assignName)
      },
      {
        title: '质检结果',
        width: 150,
        dataIndex: 'qualityInspectionResults',
        ellipsis: true,
        sorter: (a, b) => compareString(a.qualityInspectionResults, b.qualityInspectionResults),
        render: (text, record, index) => {
          let list = [
            { key: 1, label: '不合格' },
            { key: 0, label: '合格' },
          ]
          let a = list.find(item => item.key == text)
          // return <a style={{ color: text == 0 ? '#D9001B' : text == 1 ? '#00A854' : '#fff' }}>{a?.label}</a>
          return <div style={{ display: 'flex', alignItems: 'center' }}><div style={{ backgroundColor: text == 1 ? '#D9001B' : text == 0 ? '#00A854' : '#fff', width: 5, height: 5, borderRadius: 5 }}></div>&nbsp;{a?.label}</div>
        }
      },
      {
        title: '操作',
        width: 120,
        dataIndex: 'opts',
        render: (text, record) => <>
          <a onClick={() => this.openDetails(record)}>详情</a>
        </>
      },
      { dataIndex: '' }
    ],
    selectedRows: [],
    selectedRowKeys: [],
    btnLoading: false,
    addFormVisiable: false,
    visibleChooseBill: false,
    modalTitle: '批量指派',
    modalType: 0,
    chooseRecord: {},
    personList: [],
    groupList: [],
    formData: {},
  };
  componentDidMount() {
    this.getList()
    this.setState({ statusList })
    if (this.props.location.data) {
      this.setState({ searchItem: this.props.location.data }, this.fetch)
    } else {
      this.fetch()
    }
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }

  getList = () => {
    // 班组查询
    APIServiceYQ.queryGroup({ "pageNum": 1, "pageSize": 1000 }).then(res => {
      let groupList = [];
      if (res.data.code === 200) {
        groupList = res.data.data && res.data.data.data && res.data.data.data.length ? res.data.data.data : []
      }
      this.setState({ groupList })
    })
    // 人员查询   
    APIService.getUsers('pageNum=1&pageSize=1000').then(res => {
      let personList = [];
      if (res.data.code === 200) {
        personList = res.data.data && res.data.data.data && res.data.data.data.length ? res.data.data.data : []
      }
      this.setState({ personList })
    })
  }
  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true })
    const { searchItem, userId } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize
    searchItem.userId = userId

    CheckManagementService.findCheckAssignAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }

  handleCancel = e => {
    this.formChooseBill && this.formChooseBill.resetFields();
    this.setState({
      addFormVisiable: false,
      selectedRowKeys: [],
      selectedRows: [],
      btnLoading: false,
      modalTitle: '批量指派',
      modalType: 0,
      chooseRecord: {},
      visibleChooseBill: false,
    });
    this.fetch();
  };


  handleSearch = value => {
    console.log(value)
    this.setState({ searchItem: value }, this.fetch);
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }
  loadData = (value, dataSource) => {
    console.log(value, dataSource)
  }
  // 选择某一行数据
  chooseRow = record => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row === record.id) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.id);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
  };

  downloadFather = () => {
    const { selectedRows } = this.state;
  }
  fetchAll = async () => {
    const { searchItem, total } = this.state
    searchItem.pageNum = 1
    searchItem.pageSize = total
    await CheckManagementService.findCheckAssignAll(searchItem).then(res => {
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      const dataSourceAll = res.data.data.data
      const selectedRowKeys = dataSourceAll.map(item => item.id);
      this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  // 打开详情页
  openDetails = (record) => {
    const { searchItem } = this.state;
    const data = { ...record }
    // data.batchNo = [record.batchNo]
    // data.model = record.model
    localStorage.setItem('CheckManagement_searchItem', JSON.stringify(searchItem));
    localStorage.setItem('CheckManagement_detailsList', JSON.stringify(data));
    this.props.history.push({ pathname: "/CheckManagement_Details", data: { record: data, searchItem } })
  }
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({
      searchItem: {}
    }, this.fetch);
  }

  create = () => {
    this.setState({
      addFormVisiable: true
    })
  }
  onHandleSubmit = () => {
    this.formAdd.validateFields((err, value) => {
      if (err) return;
      this.setState({ btnLoading: true });
      console.log(value, 'onHandleSubmit')
      let obj = {
        ...value,
        "userId": localStorage.getItem('userId')
      }
      CheckManagementService.addWorkOrderCheckOfManual(obj).then(res => {
        this.setState({ btnLoading: false })
        if (res.data.code !== 200) {
          openModalMessage('warning', res.data.msg);
          return;
        }
        openSuccessModal(res.data.msg);
        this.handleCancel()
      }).catch(err => {
        this.setState({ btnLoading: false })
        openModalMessage('error', err.message);
      })
    })
  }

  fenpei = (type, record = {}) => {
    const { selectedRows } = this.state
    if (type === 0) {
      if (!selectedRows || !selectedRows.length) {
        openModalMessage('warning', '请选择要指派的单据！');
        return;
      }
    }
    this.setState({
      visibleChooseBill: true,
      modalTitle: type === 0 ? '批量指派' : '指派',
      modalType: type,
      chooseRecord: record
    });
  };
  submitChooseBill = () => {
    this.formChooseBill.validateFields((err, value) => {
      if (err) return;
      console.log(value);
      let data = {}
      // 个人
      if (value.type === 1) {
        data.assignType = 0
        data.assignId = value['testMachinePerson'].key
        data.assignName = value['testMachinePerson'].label
      }
      // 班组
      if (value.type === 2) {
        data.assignType = 1
        data.assignId = value['testMachineGroup'].key
        data.assignName = value['testMachineGroup'].label
      }
      data.userId = localStorage.getItem('userId')

      const { modalType, chooseRecord, selectedRows } = this.state;
      // 批量指派
      if (modalType == 0) {
        let arr = [], arr1 = []
        for (var item of selectedRows) {
          arr.push(item.batchNo);
          arr1.push(item.id);
        }
        data.ids = arr1
        data.batchNo = arr
      }
      // 单独指派
      if (modalType == 1) {
        data.ids = [chooseRecord.id]
        data.batchNo = [chooseRecord.batchNo]
      }

      this.setState({ btnLoading: true });
      CheckManagementService.addCheckAssign(data).then(res => {
        this.setState({ btnLoading: false });
        if (res.data.code !== 200) {
          openModalMessage('warning', res.data.msg);
          return;
        }
        openSuccessModal(res.data.msg);
        this.handleCancel();
      }).catch(err => {
        this.setState({ btnLoading: false });
        openModalMessage('error', err.message);
      })
    })
  };
  print = () => {
    openModalMessage('warning', '功能未开发，请联系工作人员');
  }
  render() {
    const { visibleChooseBill, modalTitle, formData, modalType, personList, groupList, btnLoading, addFormVisiable, selectList1, selectList2, selectList3, loading, dataSource, advanced, columns, pageNum, pageSize, total, selectedRowKeys, downloadLoading, searchItem, statusList } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys,
      getCheckboxProps: record => ({
        disabled: record.state == 1 || record.state == 2,
        name: record.name,
      }),
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [... this.state.selectedRowKeys];
        const rows = [... this.state.selectedRows];
        if (selected) {
          changeRows.forEach(row => {
            if (isInvalidObject(keys.find(key => key === row.id))) {
              keys.push(row.id);
              rows.push(row);
            }
          })
        } else {
          changeRows.forEach(row => {
            keys.splice(keys.indexOf(row.id), 1);
            rows.splice(rows.indexOf(row), 1);
          })
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys })
      }
    }
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            statusList={statusList}
            selectList1={selectList1}
            selectList2={selectList2}
            selectList3={selectList3}
            resetForm={this.resetForm}
            ref={node => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <BasicLayout buttons={[
          <CreateButton icon='plus' onClick={this.create} />,
          <ZPButton icon='arrow-right' onClick={() => this.fenpei(0)} />,
          <PrintButton key='2' icon="printer" onClick={this.print} />,
          // <DownLoadButton key='3' onClick={this.downloadFather} icon="download" loading={downloadLoading} />
        ]} name="质检管理" icon="table">
          <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
          <TableCustomize
            columns={columns}
            rowKey={(record) => record.id}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            allowDrafting={true}
            allowRowEdit
            allowEditable={this.loadData}
            rowSelection={rowSelection}
            onRow={(record, rowKey) => ({
              onClick: this.chooseRow.bind(this, record, rowKey)
            })}
            rowClassName={(record, index) => {
              return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
            }}
          />
          <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
        </BasicLayout>

        {/* 新增质检单 */}
        <Modal
          visible={addFormVisiable}
          destroyOnClose
          title={'新增质检单'}
          onOk={this.onHandleSubmit}
          onCancel={this.handleCancel}
          okText="确定"
          cancelText="取消"
          width={'50%'}
          maskClosable={false}
          confirmLoading={btnLoading}
        >
          <AddForm
            ref={node => (this.formAdd = node)}
            selectList1={selectList1}
          />
        </Modal>
        {/* 分配 */}
        <Modal
          visible={visibleChooseBill}
          destroyOnClose
          title={modalTitle}
          onOk={this.submitChooseBill}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
          confirmLoading={btnLoading}
        >
          <ChooseBill
            ref={node => (this.formChooseBill = node)}
            formData={formData}
            modalType={modalType}
            personList={personList}
            groupList={groupList}
          />
        </Modal>
      </div>
    );
  }
}
export default Form.create()(withRouter(CheckManagement));